package com.example.covid19.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.covid19.common.Dto.ChanDto;
import com.example.covid19.common.Dto.Editdto;
import com.example.covid19.common.Dto.QuanDto;
import com.example.covid19.common.lang.Result;
import com.example.covid19.entity.*;
import com.example.covid19.entity.SelectClass.roomcmp;
import com.example.covid19.entity.mongodb.Location;
import com.example.covid19.mapper.ChanbedMapper;
import com.example.covid19.mapper.RoomMapper;
import com.example.covid19.mapper.StudentMapper;
import com.example.covid19.service.*;
import com.example.covid19.util.MessageUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author BaiZhengChun
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/room")
public class RoomController {
    private final StudentService studentService;
    private final StudentMapper studentMapper;
    private final RoomService roomService;
    private final RoomMapper roomMapper;
    private final RoomAmountService amountService;
    @Autowired
    ChanbedService chanbedService;
    @Autowired
    ChanbedMapper chanbedMapper;
    @Autowired
    BuilderService builderService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    StustatusService stustatusService;
    @Autowired
    MessageUtil messageUtil;


    public RoomController(StudentService studentService, StudentMapper studentMapper, RoomService roomService, RoomMapper roomMapper, RoomAmountService amountService) {
        this.studentService = studentService;
        this.studentMapper = studentMapper;
        this.roomService = roomService;
        this.roomMapper = roomMapper;
        this.amountService = amountService;
    }

    /**
     * 查询当前还可以进行调换的寝室,可以使用的，符合规定的，不包含当前寝室
     *
     * @return
     */
    @RequestMapping("chequantity")
    public Result chequantity(@RequestBody Editdto editdto){
        List<roomcmp>roomcmps = roomMapper.getcmproom(editdto.getBiaoshi(), editdto.getShijian());
        JSONArray jsonArray2 = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONArray result = new JSONArray();
        Map<Integer, JSONObject> map = new HashMap<>();

        // 遍历 roomcmps，构建 map
        for (roomcmp roomcmp : roomcmps) {
            JSONObject building = map.getOrDefault(roomcmp.getLid(), new JSONObject());
            building.put("label", String.format("%d号楼", roomcmp.getLid()));
            building.put("value", roomcmp.getLid());

            JSONArray children = building.getJSONArray("children");
            if (children == null) {
                children = new JSONArray();
            }

            JSONObject room = new JSONObject();
            room.put("label", roomcmp.getRid());
            room.put("value", roomcmp.getId());
            children.add(room);

            building.put("children", children);
            map.put(roomcmp.getLid(), building);
        }

        // 将 map 转换成数组
        for (JSONObject obj : map.values()) {
            result.add(obj);
        }
        return Result.success(200,"成功",result);
    }


    /**
     *
     * @param chanbed
     * @return提交换寝室申请
     */
    @RequestMapping("/chanFrom")
    public Result chanFrom(@RequestBody Chanbed chanbed){
        Date date = new Date();
        Stustatus stustatus = new Stustatus();
        stustatus.setStudentid(chanbed.getStudentid());
        stustatus.setIsbed(1);
        Chanbed chanbed1 = new Chanbed();
        chanbed1.setStudentid(chanbed.getStudentid());
        chanbed1.setRid(chanbed.getRid());
        chanbed1.setLid(chanbed.getLid());
        chanbed1.setRaison(chanbed.getRaison());
        chanbed1.setAuid(chanbed.getAuid());
        chanbed1.setStarttime(date);
        boolean flag = chanbedService.save(chanbed1);
        System.out.println(chanbed1);
        stustatus.setBbid(chanbed1.getId());
        stustatusService.updateById(stustatus);
        //给对应导员发送消息
        messageUtil.sendone(String.valueOf(chanbed.getStudentid()),1,chanbed.getAuid());
        if (flag){
            return Result.success(200,"成功提交",null);
        }else {
            return Result.fail(400,"失败",null);
        }
    }

    /**
     *
     * @return 获取寝室基本信息，以及人数
     */
    @RequestMapping("getroomCount")
    public Result getroom_count(@RequestParam("pageNo") Integer pageNo,@RequestParam("pageSize") Integer pageSize){
        int c = roomMapper.getroom_count().size();
        HashMap<Object,Object> map = new HashMap<>();
        map.put("data",roomMapper.getCount((pageNo-1)*pageSize, pageSize));
        map.put("count",c);
        return Result.success(200,"成功",map);
    }

    /**
     *
     * @param lid
     * @param spec
     * @param rid
     * @param type
     * @return 添加寝室
     */
    @RequestMapping("addRoom")
    public Result addRoom(@RequestParam("lid")Integer lid,@RequestParam("specification")String spec,@RequestParam("rid")String rid,@RequestParam("type")String type){
        Room room = new Room();
        room.setRid(Integer.valueOf(rid));
        room.setLid(lid);
        room.setTypee(Integer.valueOf(type));
        room.setIsable(1);
        room.setSpecification(Integer.valueOf(spec));
        boolean flag = roomService.save(room);
        if (flag){
            return Result.success(200,"ok",null);
        }else {
            return Result.fail(401,"error",null);
        }
    }

    /**
     *
     * @param lid
     * @param spec
     * @param rid
     * @param type
     * @param isable
     * @param id
     * @return 修改寝室
     */
    @RequestMapping("editRoom")
    public Result editRoom(@RequestParam("lid")Integer lid,@RequestParam("specification")String spec,@RequestParam("rid")String rid,@RequestParam("type")String type,@RequestParam("isable")Integer isable,@RequestParam("id")Integer id){
        Room room = roomService.getOne(new QueryWrapper<Room>().eq("id",id));
        room.setRid(Integer.valueOf(rid));
        room.setLid(lid);
        room.setTypee(Integer.valueOf(type));
        room.setIsable(isable);
        room.setSpecification(Integer.valueOf(spec));
        boolean flag = roomService.updateById(room);
        if (flag){
            return Result.success(200,"ok",null);
        }else {
            return Result.fail(401,"error",null);
        }
    }

    /**
     *
     * @return返回的是柱状图表的数据
     */
    @RequestMapping("getzinfo")
    public Result getzinfo(){
        return Result.success(200,"ok",roomMapper.getzinfo());
    }

    /**
     *
     * @param lid
     * @param rid
     * @param sex
     * @return 获取寝室详细信息，可以选择的寝室以及已入驻的学生信息
     */
    @RequestMapping("getRoomOrder")
    public Result getRoomOrder(@RequestParam("lid") Integer lid,@RequestParam("rid") Integer rid,@RequestParam("sex") Integer sex){
        List<Builder> builderList = builderService.list(new QueryWrapper<Builder>().eq("sex",sex));
        JSONArray jsonArray = new JSONArray();
        builderList.forEach(v -> {
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("label",v.getBuildName());
                   jsonObject.put("value",v.getLid());
                   jsonArray.put(jsonObject);
                });
        System.out.println(jsonArray);
        List<Student>studentList = studentService.list(new QueryWrapper<Student>().eq("lid",lid).eq("rid",rid));
        HashMap<Object,Object> map = new HashMap<>();
        map.put("builderList",jsonArray);
        map.put("studentlist",studentList);
        return Result.success(200,"成功",map);
    }

    /**
     *
//     * @param httpServletRequest
     * @return 前端挂载时检查这个人有没有正在进行审核得换寝，有就返回数据，
     * 没有则判断最近半年内有没有换过寝室，没有则继续，有就给个数据
     * 取一个记录，之后再加一个字段，是否过期，审批后即为过期不再显示
     */
//    @RequestMapping("/ifbed")
//    public Result ifyou(HttpServletRequest httpServletRequest){
//        String s = (String) StpUtil.getLoginIdByToken(httpServletRequest.getHeader("satoken"));
//        Stustatus stustatus = stustatusService.getOne(new QueryWrapper<Stustatus>().eq("studentid",s));
//        Chanbed chanbed = chanbedService.getOne(new QueryWrapper<Chanbed>().eq("studentid",s));
//        Chanbed chanbed2 = chanbedService.getOne(new QueryWrapper<Chanbed>().eq("bbid",stustatus.getBbid()));
//        if (stustatus.getIsbed()==0&&chanbed==null){
//            return Result.success(200,"没有换寝室记录",null);
//        }
//        if (stustatus.getIsbed()==1){
//            return Result.success(201,"请等待审核",null);
//        }
////        Date date1 = new Date();
////        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
////        long dif = DateUtil.between(date1,chanbed2.getStarttime(), DateUnit.DAY);
////        if (dif<180){
////
////        }
//    }
    @RequestMapping("xiugaidb")
    public void xiugaidb(){
        String str = mongoTemplate.findById("642533d63fefe45c5e033ae2", Location.class).getGver();
        System.out.println(str);
    }

    /**
     *
     * @param sex
     * @return 添加学生的级联选择
     */
    @RequestMapping("/Stucla")
    public Result Stucla(@RequestParam("sex")Integer sex){
        List<roomcmp>roomcmps = roomMapper.getcmproom2(sex);
        List<Map<String, Object>> cascaderData = convertToCascaderFormat(roomcmps);
        return Result.success(200,"ok",cascaderData);
    }
    public List<Map<String, Object>> convertToCascaderFormat(List<roomcmp> rooms) {
        Map<Integer, List<roomcmp>> floorsMap = new HashMap<>();

        // 根据楼号（lid）进行分组
        for (roomcmp room : rooms) {
            floorsMap.putIfAbsent(room.getLid(), new ArrayList<>());
            List<roomcmp> roomList = floorsMap.get(room.getLid());
            roomList.add(room);
        }

        List<Map<String, Object>> cascaderData = new ArrayList<>();

        // 构建级联选择器格式的数据
        for (Integer lid : floorsMap.keySet()) {
            Map<String, Object> floorItem = new HashMap<>();
            floorItem.put("value", lid);
            floorItem.put("label", lid + "号楼");

            List<roomcmp> roomList = floorsMap.get(lid);
            List<Map<String, Object>> roomItems = new ArrayList<>();

            for (roomcmp room : roomList) {
                Map<String, Object> roomItem = new HashMap<>();
                roomItem.put("value", room.getRid());
                roomItem.put("label", room.getRid());
                roomItems.add(roomItem);
            }

            floorItem.put("children", roomItems);
            cascaderData.add(floorItem);
        }

        return cascaderData;
    }

}
